local cjson = require "cjson"
local _lfs = require ("lfs")
local template = require("resty.template")

local _M = {}

local function getpathes(rootpath, pathes)
    pathes = pathes or {}
    for entry in lfs.dir(rootpath) do
        if entry ~= '.' and entry ~= '..' then
            local info = {}
            local path = rootpath .. '/' .. entry
            local attr = lfs.attributes(path)
            assert(type(attr) == 'table')
            if attr.mode == 'directory' then
                getpathes(path, pathes)
            else
                local len = #(ngx.var.work_path .. '/html')
                info.base = entry
                info.path = string.sub(path, len + 1, -1)
                table.insert(pathes, info)
            end
        end
    end
    return pathes
end

function _M:index()
    local client_ip = ngx.var.remote_addr   -- ngx lua api  ngx.var 表示获取nginx自己的值，remote_addr为nginx中的客户端地址
    local photo = {}
    local th_photo = {}
    photo = getpathes(ngx.var.work_path .. '/html/img/imgs', photo)
    th_photo = getpathes(ngx.var.work_path .. '/html/img/thumbnails', th_photo)
    for k,v in ipairs(photo) do
      for kk,vv in ipairs(th_photo) do
          if vv.base == v.base then
             v.thumbnails = vv.path
          end
      end
    end

    local page = {}
    page.title = "王晋蜀的个人空间"
    page.description = "这里将深入探讨编程技术，包括linux, c, c++, rust等语言，vim，emacs, 架构设计等。:)"
    page.ip = client_ip
	local context = {photos = photo, page = page}
	template.render("viewer/index.htm", context)
end

return _M
